package admin

import (
    "net/http"
    "html/template"
    "fmt"
    "encoding/json"
    "encoding/base64"

    "github.com/gin-gonic/gin"

    "mygin/app/models"
    "mygin/app/services"
    . "mygin/app/helpers"
)

// login
func Login(c *gin.Context) {
    // 读取 Cookie
    _, err := c.Cookie("ADMIN")
    if err == nil {
        c.Redirect(302, "/admin")
    }

    files := []string{"views/admin/auth/login.html"}
    templates := template.Must(template.ParseFiles(files...))

    templates.ExecuteTemplate(c.Writer, "admin/auth/login", "")
}

// dologin
func DoLogin(c *gin.Context) {
    username := c.PostForm("username")
    password := c.PostForm("password")
    captcha_code := c.PostForm("captcha_code")
    captcha_key := c.PostForm("captcha_key")

    if len(username) == 0 {
        c.JSON(http.StatusOK, gin.H {
            "code": 200,
            "status": 0,
            "msg": "登录名不能为空！",
        })
        return
    }
    if len(password) == 0 {
        c.JSON(http.StatusOK, gin.H {
            "code": 200,
            "status": 0,
            "msg": "密码不能为空！",
        })
        return
    }
    if !services.CaptchaCheck(captcha_key, captcha_code) {
        c.JSON(http.StatusOK, gin.H {
            "code": 200,
            "status": 0,
            "msg": "验证码不正确！",
        })
        return
    }

    admin, err := models.AdminByUsername(username);
    if err != nil {
        c.JSON(http.StatusOK, gin.H {
            "code": 200,
            "status": 0,
            "msg": "您的用户名不存在！",
        })
        return
    }
    if admin.Password != Encrypt(password) {
        c.JSON(http.StatusOK, gin.H {
            "code": 200,
            "status": 0,
            "msg": "密码错误！",
        })
        return
    }

    // 设置 cookie
    cookieAdmin := models.Admin {
        Id : admin.Id,
        Username : admin.Username,
        Password : admin.Password,
        Email : admin.Email,
        Avatar : admin.Avatar,
        AutoLogout : admin.AutoLogout,
        CreatedAt : admin.CreatedAt,
    }
    fmt.Println(cookieAdmin)
    jsonAdmin, err := json.Marshal(cookieAdmin)
    if err != nil {
        panic(err)
    }

    stringAdmin := base64.URLEncoding.EncodeToString(jsonAdmin)
    // 设置 Cookie
    c.SetCookie("ADMIN", stringAdmin, 3600, "/", "", false, true)

    c.JSON(http.StatusOK, gin.H {
        "code": http.StatusOK,
        "status": 1,
        "msg": "登录成功",
    })
}

// logout
func Logout(c *gin.Context) {
    _, err := c.Cookie("ADMIN")
    if err == nil {
        // 删除 cookie
        c.SetCookie("ADMIN", "", -1, "/", "", false, true)
    }

    c.Redirect(302, "/admin")
}
